﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using P2P.Main.Model;
using P2P.Main.Session;
using P2P.Main.Util;
using P2P.Network.ExtensionMethods;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace P2P.Main.Handler
{
    public class UserHandler
    {
        private ApiProtocol apiProtocol;

        public UserHandler(ApiProtocol apiProtocol) 
        {
            this.apiProtocol = apiProtocol;
        }

        public void Login() 
        {
            string newAccountId = SnowflakeIdGenerator.Instance.NextId().ToString();
            ActiveNodeSessionManager.Instance.Flush(newAccountId,
                apiProtocol.RemoteEndPoint.Address.ToString(), apiProtocol.RemoteEndPoint.Port);

            Logger.WriteInfo($"Client at IP: {apiProtocol.RemoteEndPoint.Address.ToString()},Port: {apiProtocol.RemoteEndPoint.Port},AccountId: {newAccountId} is online.");

            JObject data = new JObject();
            data.Add("Name", "User");
            data.Add("Method", "LoginAck");
            data.Add("Version", "1.0");

            string hosts = JsonConvert.SerializeObject(SharedModel.Instance.Hosts);

            JObject param = new JObject();
            param.Add("Success", true);
            param.Add("AccountId", newAccountId);
            param.Add("Hosts", hosts);
            param.Add("AESKey", SharedModel.Instance.AESKey);
            data.Add("Params", param);  
            string ack = JsonConvert.SerializeObject(R<JObject>.Ok(data));

            apiProtocol.Socket.SendTo(ack, apiProtocol.RemoteEndPoint);
        }
    }
}
